<template>
  <!--接口渠道 列表 商户开通接口时从这里选择要开通的接口 -->
  <div class="app-container">
    <el-form
      class="search-form-new"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="auto"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="渠道类型" prop="channelType">
        <el-select
          clearable
          v-model="queryParams.channelType"
          placeholder="请选择"
        >
          <el-option label="接口" :value="1"></el-option>
          <el-option label="脚本" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否展示" prop="isShow">
        <el-select
          clearable
          v-model="queryParams.isShow"
          placeholder="请选择"
        >
          <el-option label="展示" :value="1"></el-option>
          <el-option label="不展示" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          v-hasPermi="['channelList:add']"
          type="success"
          icon="el-icon-plus"
          @click="handleAdd"
          >新增</el-button
        >
        <el-button
          v-hasPermi="['channelList:add']"
          type="success"
          plain
          @click="asyncAttr"
          >同步属性</el-button
        >
      </el-form-item>
      <el-form-item class="btns">
        <!-- 上传模板 -->
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
          :on-error="handleError"
          :show-file-list="true"
          accept=".xlsx"
        >
          <el-button type="warning" icon="el-icon-top">上传模板</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <div class="table_box">
      <div class="tip">
        本页数据尽量不要修改。此修改不影响已开通的接口里的信息，以及推送记录等等
      </div>

      <el-table
        stripe
        v-loading="loading"
        :data="accountList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" prop="id" width="100" />
        <el-table-column label="渠道名称" prop="name" min-width="150"/>
        <el-table-column label="渠道类型" prop="channelType" width="100">
          <template slot-scope="scope">
            <div>
              <el-tag type="primary" v-if="scope.row.channelType == 1"
                >接口</el-tag
              >
              <el-tag type="warning" v-if="scope.row.channelType == 2"
                >脚本</el-tag
              >
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="关联用户" prop="userName" /> -->
        <el-table-column label="渠道联系方式" prop="contact" min-width="150">
        </el-table-column>
        <el-table-column
          label="技术联系方式"
          prop="serviceContact"
          min-width="150"
        >
        </el-table-column>
        <el-table-column label="关联游戏" prop="gameNames" show-overflow-tooltip min-width="150" />
        <el-table-column label="备注" prop="remark" show-overflow-tooltip/>
        <el-table-column label="排序" prop="sort"> </el-table-column>
        <el-table-column label="是否展示" prop="isShow">
          <template slot-scope="scope">
            <div>
              {{ commonMaps.isYesMap[scope.row.isShow] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="支持翻新" prop="isRenovate">
          <template slot-scope="scope">
            <div>
              {{ commonMaps.isYesMap[scope.row.isRenovate] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="推送间隔(秒)" prop="reqSpaceTime">
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['channelList:edit']"
              type="edit"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              style="color: red"
              v-hasPermi="['channelList:edit']"
              type="text"
              size="mini"
              @click="shuxingjz(scope.row)"
              >属性校正</el-button
            >
            <!-- <el-button type="text" icon="el-icon-edit" @click="addGame(scope.row)">关联游戏</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="渠道名称" prop="name">
          <el-input
            v-model="form.name"
            style="width: 200px"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="渠道类型" prop="channelType">
          <el-radio v-model="form.channelType" :label="1">接口</el-radio>
          <el-radio v-model="form.channelType" :label="2">脚本</el-radio>
        </el-form-item>
        <el-form-item label="详情页URL" prop="infoUrl">
          <el-input
            type="textarea"
            v-model="form.infoUrl"
            style="width: 600px"
            placeholder="请输入商品详情页的url，商品ID用xxx代替"
          />
        </el-form-item>
        <el-form-item label="关联游戏" prop="name">
          <el-checkbox-group
            style="width: 800px"
            @change="gameChange"
            v-model="selectGameIds"
          >
            <el-checkbox
              :label="item.id"
              v-for="item in gameList"
              :key="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="CODE" prop="code">
          <el-input
            style="width: 200px"
            v-model="form.code"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="通道默认值" prop="type">
          <el-input
            style="width: 200px"
            v-model="form.type"
            placeholder="请输入通道"
          />
        </el-form-item><br />
        <el-form-item label="渠道联系方式" prop="contact">
          <el-input
            style="width: 200px"
            v-model="form.contact"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="技术联系方式" prop="serviceContact">
          <el-input
            style="width: 200px"
            v-model="form.serviceContact"
            placeholder="请输入"
          /> </el-form-item
        ><br />
        <el-form-item label="是否展示">
          <el-radio-group v-model="form.isShow">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支持翻新">
          <el-radio-group v-model="form.isRenovate">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item><br />
        <el-form-item label="推送间隔(秒)" prop="reqSpaceTime">
          <el-input-number
            v-model="form.reqSpaceTime"
            placeholder="请输入"
            :min="0"
            :step="1"
          /> </el-form-item
        >
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            placeholder="请输入"
          /> </el-form-item
        ><br />
        <el-form-item label="备注" prop="remark">
          <el-input
            style="width: 600px"
            type="textarea"
            rows="5"
            v-model="form.remark"
            placeholder="请输入"
          /> </el-form-item
        ><br />
        <!-- 脚本每月扣虞豆最多限制 -->

        <el-form-item
          label="虞豆限制"
          prop="yudouLimit"
          v-if="form.channelType == 2"
        >
          <el-input-number
            v-model="form.yudouLimit"
            placeholder="脚本每月扣虞豆最多限制"
          />
          <span>豆</span>
          <span class="tip" style="margin-left: 10px"
            >脚本按次扣费，设置脚本每月扣虞豆限制，当月扣除到量后续推送将不扣费。</span
          >
        </el-form-item>
        <br />

        <el-form-item prop="buyWay">
          <span slot="label">
            <el-tooltip
              content="控制该接口渠道开通时一次性永久开通，还是按时长开通，修改该参数不影响已开通的用户。"
              placement="top"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
            计费方式
          </span>
          <el-radio-group v-model="form.buyWay">
            <el-radio
              v-for="(item, key) in commonMaps.buyWayMap"
              :key="key"
              :label="key"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="monthAmount" label="">
          <span slot="label">
            <el-tooltip
              content="开通该功能多少虞豆，计费方式为月租时填写一个月的费用"
              placement="top"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
            开通虞豆
          </span>
          <el-input
            type="number"
            style="width: 120px"
            v-model="form.monthAmount"
            placeholder=""
          />
        </el-form-item>
        <el-form-item prop="minMonthDuration" v-if="form.buyWay == 2">
          <span slot="label">
            <el-tooltip
              content="控制该分组开通时最低开通月数。"
              placement="top"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
            起开时长
          </span>
          <el-input-number
            style="width: 150px"
            v-model="form.minMonthDuration"
            placeholder=""
          />月 </el-form-item
        ><br />
        <el-form-item label="参数配置" prop="">
          <div class="canshu-box" v-loading="loading">
            <el-table :data="config" border style="width: 100%">
              <el-table-column prop="key" label="字段key" width="120">
              </el-table-column>
              <el-table-column prop="date" label="字段名称">
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入内容"
                    v-model="scope.row.name"
                    clearable
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="是否启用" width="130">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.isShow"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                  ></el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="address" label="是否必填" width="130">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.isMust"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                  ></el-switch>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 属性校正弹出层 -->
    <el-dialog
      title="属性校正"
      :visible.sync="dioShuxingjiaozheng"
      width="1000px"
      append-to-body
      @close="closefn"
    >
      <el-form ref="form" :inline="true" :model="formAttr" label-width="auto">
        <el-form-item label="渠道名称" prop="name">
          <el-select
            filterable
            clearable
            v-model="name"
            @change="changefn"
            placeholder="请选择"
          >
            <el-option
              v-for="item in listAttr"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <br />
        <el-form-item label="saleKey" prop="code">
          <el-input
            style="width: 333px"
            v-model="formAttr.saleKey"
            placeholder="请输入"
          />
        </el-form-item>
        <br />
        <el-form-item label="other" prop="code">
          <el-input
            style="width: 333px"
            v-model="formAttr.other"
            placeholder="请输入"
          />
        </el-form-item>
        <br />
        <el-form-item label="twoOther" prop="code">
          <el-input
            style="width: 333px"
            v-model="formAttr.twoOther"
            placeholder="请输入"
          />
        </el-form-item>
        <br />
        <el-form-item label="threeOther" prop="code">
          <el-input
            style="width: 333px"
            v-model="formAttr.threeOther"
            placeholder="请输入"
          />
        </el-form-item>
        <br />
        <el-form-item label="fourOther" prop="code">
          <el-input
            style="width: 333px"
            v-model="formAttr.fourOther"
            placeholder="请输入"
          />
        </el-form-item>
        <br />
        <el-form-item label="fiveOther" prop="code">
          <el-input
            style="width: 333px"
            v-model="formAttr.fiveOther"
            placeholder="请输入"
          />
        </el-form-item>
        <br />
        <el-form-item label="sixOther" prop="code">
          <el-input
            style="width: 333px"
            v-model="formAttr.sixOther"
            placeholder="请输入"
          />
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="closefn">取 消</el-button>
          <el-button type="primary" @click="submitFormAttr">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>

    <asyncAttrDialog ref="asyncAttrDialog"></asyncAttrDialog>
  </div>
</template>

<script>
import {
  delAccount,
  exportAccount,
  getQudaoListInfo,
  listInfoXIN,
} from "@/api/info/check";

import gameListApi from "@/api/gameConfig/gameList";
import interfaceChannelApi from "@/api/interfaceChannel/index";
import supplyConfigApi from "@/api/system/supplyConfig";
import VirtualSelect from "@/components/VirtualSelect.vue";
import asyncAttrDialog from "./asyncAttrDialog.vue";
export default {
  name: "ChannelList",
  components: { VirtualSelect ,asyncAttrDialog},
  dicts: [],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 账号校验表格数据
      accountList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        isShow: "",
      },
      qrCodeList: [],
      // 表单参数
      form: {
        name: "",
        contact: "",
        serviceId: "",
        serviceName: "",
        serviceContact: "",
        isShow: 1,
        sort: "",
        remark: "",
        gameIds: "",
        gameNames: "",
        type: "",
        yudouLimit: "",
        infoUrl: "",
        isRenovate:2,
        reqSpaceTime:0
      },
      gameList: [],
      selectGameIds: [],
      selectGameNames: [],
      allUsers: [],
      initConfig: [
        {
          key: "saleKey",
          name: "字段1",
          id: 1,
          isShow: false,
          isMust: false,
        },
        {
          key: "other",
          name: "字段2",
          id: 2,
          isShow: false,
          isMust: false,
        },
        {
          key: "twoOther",
          name: "字段3",
          id: 3,
          isShow: false,
          isMust: false,
        },
        {
          key: "threeOther",
          name: "字段4",
          id: 4,
          isShow: false,
          isMust: false,
        },
        {
          key: "fourOther",
          name: "字段5",
          id: 5,
          isShow: false,
          isMust: false,
        },
        {
          key: "fiveOther",
          name: "字段6",
          id: 6,
          isShow: false,
          isMust: false,
        },
        {
          key: "sixOther",
          name: "字段7",
          id: 7,
          isShow: false,
          isMust: false,
        },
      ],
      name: "",
      formAttr: {
        saleKey: "",
        other: "",
        twoOther: "",
        threeOther: "",
        fourOther: "",
        fiveOther: "",
        sixOther: "",
        saleName: "",
        interfaceUserId: "",
      },
      IdAttr: null,
      nameAtttr: null,
      dioShuxingjiaozheng: false,
      config: [],
      // 表单校验
      rules: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        type: [{ required: true, message: "请输入", trigger: "blur" }],
        code: [{ required: true, message: "请输入", trigger: "blur" }],
        contact: [{ required: true, message: "请输入", trigger: "blur" }],
        serviceContact: [
          { required: true, message: "请输入", trigger: "blur" },
        ],
        buyWay: [
          { required: true, message: "计费方式不能为空", trigger: "change" },
        ],
        monthAmount: [
          { required: true, message: "费用不能为空", trigger: "change" },
        ],
        minMonthDuration: [
          {
            required: true,
            message: "最低开通时长不能为空",
            trigger: "change",
          },
        ],
      },
      listAttr: [],
      uploadUrl: "",
    };
  },
  created() {
    this.uploadUrl = process.env.VUE_APP_BASE_API + "/inter/uploadTemplate";
    this.getList();
    this.getGameList();
  },
  methods: {
    beforeUpload(file) {
      const isXLSX =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!isXLSX) {
        this.$message.error("只能上传 .xlsx 格式的Excel文件！");
      }
      return isXLSX;
    },
    handleSuccess(response, file, fileList) {
      this.$message.success("上传成功！");
      // 这里可以处理后端返回的数据
    },
    handleError(err, file, fileList) {
      this.$message.error("上传失败！");
    },
    //属性校正
    async shuxingjz(item) {
      this.dioShuxingjiaozheng = true;
      const res = await getQudaoListInfo(item.id);
      console.log(res);
      this.listAttr = res.data;
    },
    closefn() {
      this.dioShuxingjiaozheng = false;
      this.formAttr = {
        saleKey: "",
        other: "",
        twoOther: "",
        threeOther: "",
        fourOther: "",
        fiveOther: "",
        sixOther: "",
        saleName: "",
        interfaceUserId: "",
      };
    },
    changefn(e) {
      console.log("e", e);
      const obj = this.listAttr.filter((item) => item.name == e);
      this.formAttr = obj[0];
      this.IdAttr = obj[0].interfaceUserId;
      this.nameAtttr = obj[0].interfaceUserName;
      localStorage.setItem("listAttrInfo", JSON.stringify(this.formAttr));
    },
    async submitFormAttr() {
      const res = await listInfoXIN(this.formAttr);
      if (res.code == 200) {
        this.$message.success("操作成功!");
        this.dioShuxingjiaozheng = false;
        localStorage.setItem("AttrList", JSON.stringify(res.data));
        this.$router.push({
          path: "/api/index/SHUXINGJZ",
          query: {
            Id: this.IdAttr,
            Name: this.nameAtttr,
            paramsData: JSON.stringify(this.formAttr),
          },
        });
      }
    },
    // // 获取所有用户
    getAllUserList(val) {
      supplyConfigApi.getAllUserList().then((res) => {
        this.allUsers = res.rows;
      });
    },

    getList() {
      this.loading = true;
      interfaceChannelApi
        .interfaceChannelList(this.queryParams)
        .then((response) => {
          this.accountList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
    },
    // 游戏列表
    async getGameList() {
      let res = await gameListApi.getGameList();
      // console.log("%c Line:278 🍫 res", "color:#465975", res);
      res.rows.forEach((r) => {
        r.id = String(r.id);
      });
      this.gameList = res.rows;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 选择用户改变
    userChange(e) {
      // console.log("%c Line:217 🍯 e", "color:#4fff4B", e);
      this.allUsers.forEach((r) => {
        if (r.userId == e) {
          this.form.userName = r.nickName;
          this.form.contact = r.phonenumber;
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        name: "",
        contact: "",
        serviceId: "",
        serviceName: "",
        serviceContact: "",
        isShow: 1,
        sort: "",
        remark: "",
        gameIds: "",
        gameNames: "",
        type: "",
        buyWay: "",
        monthAmount: "",
        minMonthDuration: "",
        yudouLimit: "",
        infoUrl: "",
        isRenovate:2,
        reqSpaceTime:0
      };
      this.selectGameIds = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: null,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    //同步属性 打开窗口
    asyncAttr(){
      this.$refs.asyncAttrDialog.open()

    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增接口渠道";
      this.config = JSON.parse(JSON.stringify(this.initConfig));
      this.$set(this.form, "buyWay", "2");
      this.$set(this.form, "channelType", 1);

      this.form.minMonthDuration = 1;
      // this.getUserList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = JSON.parse(JSON.stringify(row));
      if (this.form.buyWay) this.form.buyWay = String(this.form.buyWay);
      if (this.form.gameIds) {
        this.selectGameIds = this.form.gameIds.split(",");
      }
      if (this.form.configTemplate) {
        this.config = JSON.parse(this.form.configTemplate);
      } else {
        this.config = JSON.parse(JSON.stringify(this.initConfig));
      }
      // this.getUserList()
      this.open = true;
      this.title = "修改渠道";
    },
    // 选择游戏改变
    gameChange(e) {
      console.log("%c Line:350 🍕 e", "color:#93c0a4", e);
      let ids = [];
      let names = [];
      if (e && e.length) {
        this.gameList.forEach((game) => {
          if (e.indexOf(game.id) > -1) {
            ids.push(game.id);
            names.push(game.name);
          }
        });
        this.form.gameIds = ids.join(",");
        this.form.gameNames = names.join(",");
      } else {
        this.form.gameIds = "";
        this.form.gameNames = "";
      }
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    // 标题图片移除
    handleAvatarRemove(response, file) {
      this.form.qrCode = "";
      this.qrCodeList = [];
    },
    // 标题图片上传成功
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        let url = res.data.filePath;
        let name = res.data.fileName;
        let param = {};
        param.url = url;
        param.name = name;
        this.qrCodeList.push(param);
        this.form.qrCode = res.data.filePath;
        console.log(
          "%c Line:259 🥪 this.form.qrCode",
          "color:#e41a6a",
          this.form.qrCode
        );
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.configTemplate = JSON.stringify(this.config);
          if (this.form.id != null) {
            interfaceChannelApi.edit(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            interfaceChannelApi
              .addInterfaceChannel(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除id为"' + ids + '"的数据项？')
        .then(function () {
          return delAccount(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
.tip {
  text-align: right;
  color: #ff0000;
  font-size: 14px;
}

.canshu-box {
  width: 600px;
}

::v-deep .el-upload-list__item {
  display: none;
}
</style>
